import 'package:enjoy_community_flutter/utils/http.dart';
import 'package:enjoy_community_flutter/utils/logger.dart';
import 'package:enjoy_community_flutter/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String apiKey = 'ca609627719d04a8cb7f2880f74bfb6d';
  String baseUrl = 'https://restapi.amap.com/v3';
  String address = '';
  List nearbyCommunities = [];

  @override
  void initState() {
    // 请求位置权限
    requestLocationPermission();
    super.initState();
  }

  // 请求位置权限
  Future<void> requestLocationPermission() async {
    if (await Permission.location.request().isGranted) {
      // 授权成功
      ToastUtil.showSuccess('授权位置成功');
      getCurrentLocation();
    } else {
      // 授权失败
      ToastUtil.showError('授权位置失败');
    }
  }

  // 获取当前设备的位置信息 - 经纬度
  Future<void> getCurrentLocation() async {
    late LocationSettings locationSettings;
    // 针对于不同的平台 android iOS macOS Web 添加特定的配置
    if (defaultTargetPlatform == TargetPlatform.android) {
      // 设置高精度定位 100米距离过滤等
      locationSettings = AndroidSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 100,
          forceLocationManager: true,
          intervalDuration: const Duration(seconds: 10),
          //(Optional) Set foreground notification config to keep the app alive
          //when going to the background
          foregroundNotificationConfig: const ForegroundNotificationConfig(
            notificationText:
                "Example app will continue to receive your location even when you aren't using it",
            notificationTitle: "Running in Background",
            enableWakeLock: true,
          ));
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        // 位置的持续时间5分钟
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    // supply location settings to getCurrentPosition
    try {
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      // logger.i(position);
      ToastUtil.showSuccess(
          '位置信息 - 纬度${position.latitude} - 经度 ${position.longitude}');
      // 创新港 经纬度： 121.612112,31.034633
      // reverseGeocoding(position.longitude, position.latitude);
      // queryNearbyCommunities(position.longitude, position.latitude);
      reverseGeocoding(121.612112, 31.034633);
      queryNearbyCommunities(121.612112, 31.034633);
      // 搜索附近社区
    } catch (e) {
      ToastUtil.showError('位置获取失败$e');
    }
  }

  // 逆地理编码获取位置
  Future<void> reverseGeocoding(double longitude, double latitude) async {
    String url =
        '$baseUrl/geocode/regeo?key=$apiKey&location=$longitude,$latitude';
    try {
      var response = await http.get(url);
      // logger.i(response['regeocode']['formatted_address']);
      setState(() {
        address = response['regeocode']['formatted_address'];
      });
    } catch (e) {
      logger.e('逆地址编码获取位置失败$e');
    }
  }

  // 获取附近社区
  Future<void> queryNearbyCommunities(double longitude, double latitude) async {
    // https: //restapi.amap.com/v3/place/around?key=<用户的key>&location=116.473168,39.993015&radius=10000&types=011100
    String url =
        '$baseUrl/place/around?key=$apiKey&location=$longitude,$latitude&radius=1500&keywords=住宅小区';
    try {
      final res = await http.get(url);
      for (var item in res['pois']) {
        setState(() {
          nearbyCommunities.add({'name': item['name']});
        });
      }
    } catch (e) {
      logger.e('获取附近社区失败 $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  ElevatedButton(
                    onPressed: () {
                      getCurrentLocation();
                    },
                    style: ElevatedButton.styleFrom(
                      minimumSize: Size.zero,
                      padding: const EdgeInsets.only(
                          top: 3, bottom: 3, left: 5, right: 5),
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: const Row(
                      children: [
                        Icon(Icons.location_searching_outlined,
                            color: Colors.blue),
                        SizedBox(width: 2),
                        Text(
                          '重新定位',
                          style: TextStyle(color: Colors.blue),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: nearbyCommunities.map((item) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/building_list',
                          arguments: {'point': item['name']});
                    },
                    child: Container(
                      color: Colors.white,
                      padding: const EdgeInsets.all(10),
                      child: Row(
                        children: [
                          Expanded(child: Text(item['name'])),
                          const Row(
                            children: [
                              Icon(
                                Icons.arrow_forward_ios,
                                size: 16,
                                color: Colors.black,
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                  );
                }).toList())
          ],
        ));
  }
}
